<template>
    <!-- 添加或修改物资采购申请对话框 -->
    <el-dialog 
      :title="title" 
      :modelValue="visible"
      ref="dialogRef"
      @update:modelValue="emit('update:visible', $event)"
      width="900px" 
      append-to-body
      class="seal-dialog"
      @opened="handleDialogOpen"
    >
      <template #default>
        <div style="padding-right: 24px;">
          <el-form ref="admItemApplyFormRef" :model="form" :rules="rules" label-width="140px" label-position="left" style="padding: 20px 0 20px 24px">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="申请人" prop="applyName">
                  <el-input v-model="form.applyName" placeholder="请输入申请人名称" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="申请部门" prop="deptId">
                  <el-tree-select
                    v-model="form.deptId"
                    :data="deptTree"
                    placeholder="请选择申请部门"
                    :props="{ label: 'label', value: 'id', children: 'children' }"
                    check-strictly
                    filterable
                    :default-expand-all="true"
                    style="width: 100%"
                    @visible-change="handleVisibleChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="申请日期" prop="applyTime">
                  <el-date-picker clearable
                    v-model="form.applyTime"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择申请时间"
                    :default-value="new Date()"
                    style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="类别" prop="type">
                  <el-select v-model="form.type"  :empty-values="[null, undefined]" placeholder="请选择类别" style="width: 100%">
                    <el-option
                      v-for="item in item_apply_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="物品名称" prop="itemName">
                  <el-input v-model="form.itemName" placeholder="请输入物品名称" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="品牌名称" prop="brandName">
                  <el-input v-model="form.brandName" placeholder="请输入品牌名称" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="规格型号" prop="specificationName">
                  <el-input v-model="form.specificationName" placeholder="请输入规格型号" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="用品说明" prop="describe">
                  <el-input v-model="form.describe" placeholder="请输入用品说明" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="数量" prop="amount">
                  <el-input v-model="form.amount" placeholder="请输入数量" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="单位" prop="unit">
                  <el-input v-model="form.unit" placeholder="请输入单位" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="单价" prop="price">
                  <el-input v-model="form.price" placeholder="请输入单价" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="质量要求" prop="qualityRequirement">
                  <el-input v-model="form.qualityRequirement" placeholder="请输入质量要求" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="到货时间" prop="arrivalTime">
                  <el-date-picker clearable
                    v-model="form.arrivalTime"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择到货时间"
                    style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" :rows="3" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
</template>

<script setup name="AdmItemApply" lang="ts">
import { listAdmItemApply, addAdmItemApply, updateAdmItemApply } from '@/api/general/administration/item/apply';
import { AdmItemApplyVO, AdmItemApplyForm } from '@/api/general/administration/item/apply/types';
import type { DeptTreeNode } from '@/api/general/administration/seal/types';
import { getDeptTree } from '@/api/general/administration/seal';
import type { FormRules, ElDialog  } from 'element-plus';
import { useUserStore } from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  visible: {
    type: Boolean,
    default: false
  }
});

const buttonLoading = ref(false);
const admItemApplyFormRef = ref<ElFormInstance>();
const loading = ref(true);
const admItemApplyList = ref<AdmItemApplyVO[]>([]);
const total = ref(0);
const emit = defineEmits(['update:visible', 'success']);
// 引入数据字典
const { item_apply_type } = toRefs<any>(proxy?.useDict('item_apply_type'));

// 部门树初始化
const deptTree = ref<DeptTreeNode[]>([]);
const deptTreeSelectRef = ref();

// 用户信息
const userStore = useUserStore();

// dialogVisible 监听
const dialogRef = ref<InstanceType<typeof ElDialog > | null>(null);;

// 本地时间格式化函数
const formatLocalDate = (date = new Date()) => {
  const padZero = num => String(num).padStart(2, '0');
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`;
};

const initFormData: AdmItemApplyForm = {
  id: undefined,
  applyId: userStore.userId,
  applyName: userStore.name,
  deptId: undefined,
  applyTime: formatLocalDate(),
  type: undefined,
  itemName: undefined,
  brandName: undefined,
  specificationName: undefined,
  describe: undefined,
  amount: undefined,
  unit: undefined,
  price: undefined,
  qualityRequirement: undefined,
  arrivalTime: undefined,
  status: 0,
  remark: undefined,
}
const form = ref<AdmItemApplyForm>({ ...initFormData });
const rules = reactive<FormRules>({
  // 申请人（必填，2-10个字符）
  applyName: [
    { required: true, message: '请输入申请人姓名', trigger: 'blur' },
  ],
  // 申请部门（必填）
  deptId: [
    { required: true, message: '请选择申请部门', trigger: 'change' }
  ],
  // 日期（必填，需为合法日期）
  date: [
    { 
      required: true, 
      message: '请选择申请日期', 
      trigger: 'change',
      validator: (_, value, callback) => {
        if (!value) callback(new Error('请选择日期'));
        else if (isNaN(new Date(value).getTime())) callback(new Error('日期格式无效'));
        else callback();
      }
    }
  ],
  // 类别（必填，只能是两种选项之一）
  type: [
    { 
      required: true, 
      message: '请选择类别', 
      trigger: 'change',
      validator: (_, value, callback) => {
        const validTypes = ['0', '1'];
        if (!validTypes.includes(value)) {
          callback(new Error(`类别必须是${validTypes.join('或')}`));
        } else {
          callback();
        }
      }
    }
  ],
  // 物品名称（必填，1-50字符）
  itemName: [
    { required: true, message: '请输入物品名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在1到50个字符', trigger: 'blur' }
  ],
  // 品牌名称
  brandName: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
  ],
  // 规格型号
  specificationName: [
    { required: true, message: '请输入规格型号', trigger: 'blur' },
  ],
  // 用品说明
  describe: [
    { required: true, message: '请输入用品说明', trigger: 'blur' },
  ],
  // 数量（必填，必须为大于0的整数）
  amount: [
  { required: true, message: '请输入数量', trigger: 'blur' },
    { 
      pattern: /^\d+(\.\d+)?$/,
      message: '必须为数字',
      trigger: 'blur'
    }
  ],
  // 单位（必填）
  unit: [
    { required: true, message: '请选择单位', trigger: 'change' }
  ],
  // 单价（必填，必须为数字且大于0）
  price: [
    { required: true, message: '请输入单价', trigger: 'blur' },
    { 
      validator: (_, value, callback) => {
        const num = Number(value);
        if (isNaN(num)) callback(new Error('必须为数字'));
        else if (num <= 0) callback(new Error('必须大于0'));
        else callback();
      },
      trigger: 'blur'
    }
  ],
  // 质量要求
  qualityRequirement: [
    { required: true, message: '请输入质量要求', trigger: 'blur' },
  ],
  // 到货时间（必填，且不能早于申请时间）
  arrivalTime: [
    { required: true, message: '请选择到货时间', trigger: 'change' },
    {
      validator: (_, value, callback) => {
        if (!value) return callback(new Error('请选择日期'));
        const selectedDate = new Date(value);
        const applyDate = new Date(form.value.applyTime);
        applyDate.setHours(0, 0, 0, 0);
        selectedDate.setHours(0, 0, 0, 0);
        if (selectedDate < applyDate) {
          callback(new Error('到货时间不能早于申请时间'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
});

// 对话框打开时滚动到顶部
const handleDialogOpen = async () => {
  await nextTick(); // 确保 DOM 渲染完成
  // 使用 document.querySelector 精准获取 Teleport 后的 el-dialog__body
  const scrollBody = document.querySelector<HTMLElement>('.seal-dialog .el-dialog__body');
  if (scrollBody) {
    scrollBody.scrollTop = 0; // 滚动到顶部
  } else {
    console.warn('未找到 el-dialog__body');
  }
};

/** 查询物资采购申请列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAdmItemApply();
  admItemApplyList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}


/** 取消按钮 */
const cancel = () => {
  reset();
  emit('update:visible', false);
}

/** 表单重置 */
const reset = () => {
  Object.assign(form.value, initFormData);
  admItemApplyFormRef.value?.resetFields();
  // 如果是新增，获取编号
  // if (!form.value.id) {
  //   await getNumber();
  // }
}


/** 提交按钮 */
const submitForm = () => {
  admItemApplyFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAdmItemApply(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addAdmItemApply(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      emit('update:visible', false);
      emit('success');
      await getList();
    }
  });
}

// 获取部门树
const fetchDeptTree = async () => {
  try {
    const res = await getDeptTree();
    const processNode = (node: any) => {
      if (node.children && node.children.length > 0) {
        // 有子节点 → 禁用，但允许展开
        node.disabled = true;
        node.children.forEach(processNode); // 递归处理子节点
      } else {
        // 叶子节点 → 可选
        node.disabled = false;
      }
    };
    if (Array.isArray(res.data)) {
      res.data.forEach(processNode);
    }
    deptTree.value = res.data;
  } catch (error) {
    console.error('获取部门树失败:', error);
    proxy?.$modal.msgError('获取部门树失败');
  }
};

// 下拉框打开时展开全部节点
const handleVisibleChange = (visible: boolean) => {
  if (visible) {
    // 展开全部节点（treeSelect 内部的 tree 是 el-tree 实例）
    setTimeout(() => {
      const tree = deptTreeSelectRef.value?.$refs?.tree;
       tree?.expandAll?.();
    }, 0);
  }
};

// 日期date转换string方法
function formatDate(str?: string | Date) {
  if (!str) return undefined;
  const date = typeof str === 'string' ? new Date(str) : str;
  const y = date.getFullYear();
  const m = (date.getMonth() + 1).toString().padStart(2, '0');
  const d = date.getDate().toString().padStart(2, '0');
  return `${y}-${m}-${d}`;
}

// 子方法打开弹窗数据处理
const openDialog = async (data?: AdmItemApplyForm) => {
  if (data) {
    // 回显数据时，做类型和日期转换
    Object.assign(form.value, {
      ...data,
      // type 必须是字符串，保证 ElSelect 正确显示
      type: data.type !== undefined ? String(data.type) : undefined,
      // applyTime 转为 Date 对象（如果你使用 ElDatePicker）
      applyTime: formatDate(data.applyTime),
      arrivalTime: formatDate(data.arrivalTime),
    });
  } else {
    // 新增时重置表单
    await reset();
  }
};


// 暴露方法给父组件
defineExpose({
  reset,
  openDialog
});

onMounted(() => {
  fetchDeptTree();
});
</script>
<style scoped>
.seal-dialog :deep(.el-dialog__header) {
  text-align: center;
}

/* 合同对话框中的用户选择器样式 */
.user-selector-container {
  width: 100%;
}

.user-selector-container .selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
  min-height: 20px;
}

/* 对话框样式优化 */
:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto !important;
  display: block; /* 确保是块级元素 */
}
</style>